import pygame
import sys
import os
from typing import List, Dict, Optional, Tuple
import math

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from game.game_manager import GameManager
from champions.base_champion import Champion
class GraphicsUI:
    def __init__(self):
        self.selecting_item_for_team = None  # 正在为哪个队伍选择物品
        self.item_selection_buttons = []     # 物品选择按钮
        self.selected_item_index = None 
        pygame.init()
        self.screen_width = 1200
        self.screen_height = 800
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
        pygame.display.set_caption("League of Chang'An")
        
        self.colors = {
            'background': (20, 25, 40),     
            'primary': (139, 69, 19),       
            'secondary': (205, 133, 63),    
            'accent': (255, 215, 0),         
            'text': (255, 255, 255),     
            'text_dark': (50, 50, 50),       
            'success': (0, 255, 0),      
            'error': (255, 0, 0),          
            'warning': (255, 165, 0),        
            'info': (0, 191, 255),      
            'button': (70, 130, 180),        
            'button_hover': (100, 149, 237), 
            'panel': (30, 35, 50),         
            'border': (139, 69, 19)          
        }
        
        def _sys_font(size):
            try:
                return pygame.font.SysFont(['Microsoft YaHei UI', 'Microsoft YaHei', 'SimHei', 'Arial Unicode MS', 'Arial'], size)
            except Exception:
                return pygame.font.Font(None, size)

        self.fonts = {
            'title': _sys_font(48),
            'large': _sys_font(36),
            'medium': _sys_font(24),
            'small': _sys_font(18),
            'tiny': _sys_font(14)
        }
        
        self.game_manager = GameManager()
        self.current_screen = "main_menu"
        self.current_team1 = []
        self.current_team2 = []
        self.selected_champion = None
        self.selected_team = 1
        self.battle_active = False
        self.battle_turn = 0
        
        self.buttons = []
        self.panels = []
        self.animations = []
        self.team_button_rects = {
            'team1': pygame.Rect(50, 420, 100, 30),
            'team2': pygame.Rect(650, 420, 100, 30)
        }
        
        self.clock = pygame.time.Clock()
        self.fps = 60
        self.turn_interval_ms = 1000 
        self._last_turn_ms = 0
        
        self._initialize_ui()
    
    def _initialize_ui(self):
        self._create_main_menu_buttons()
        
        self._create_champion_panels()
    
    def _create_main_menu_buttons(self):
        button_width = 200
        button_height = 50
        start_x = self.screen_width // 2 - button_width // 2
        start_y = 300
        
        buttons = [
            ("Select a champion", start_x, start_y, button_width, button_height, "champion_selection"),
            ("Item Management", start_x, start_y + 70, button_width, button_height, "item_management"),
            ("Start battle", start_x, start_y + 140, button_width, button_height, "start_battle"),
            ("Save the game", start_x, start_y + 210, button_width, button_height, "save_game"),
            ("Load the game", start_x, start_y + 280, button_width, button_height, "load_game"),
            ("Game Information", start_x, start_y + 350, button_width, button_height, "game_info"),
            ("Exit the game", start_x, start_y + 420, button_width, button_height, "exit_game")
        ]
        
        for text, x, y, w, h, action in buttons:
            self.buttons.append({
                'text': text,
                'rect': pygame.Rect(x, y, w, h),
                'action': action,
                'hover': False
            })
    
    def _create_champion_panels(self):
        self.panels.append({
            'name': 'team1_panel',
            'rect': pygame.Rect(50, 100, 500, 300),
            'title': 'team 1',
            'champions': []
        })
        
        self.panels.append({
            'name': 'team2_panel',
            'rect': pygame.Rect(650, 100, 500, 300),
            'title': 'team2',
            'champions': []
        })
        
        self.panels.append({
            'name': 'available_panel',
            'rect': pygame.Rect(50, 450, 1100, 300),
            'title': 'available champion',
            'champions': []
        })
    
    def run(self):
        running = True
        
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    self._handle_click(event.pos)
                elif event.type == pygame.MOUSEMOTION:
                    self._handle_hover(event.pos)
                elif event.type == pygame.KEYDOWN:
                    self._handle_keypress(event.key)
            
            self._update()
            
            self._draw()
            
            pygame.display.flip()
            self.clock.tick(self.fps)
        
        pygame.quit()
        sys.exit()
    
    def _handle_click(self, pos):
        if self.current_screen == "main_menu":
            for button in self.buttons:
                if button['rect'].collidepoint(pos):
                    self._execute_action(button['action'])
                    return
        
        elif self.current_screen == "champion_selection":
            if self.team_button_rects['team1'].collidepoint(pos):
                self.selected_team = 1
                return
            if self.team_button_rects['team2'].collidepoint(pos):
                self.selected_team = 2
                return
            self._handle_champion_click(pos)
        elif self.current_screen == "item_management":  
            if self.selecting_item_for_team:
                self._handle_item_selection_click(pos)  # 物品选择界面的点击
            else:
                self._handle_item_management_click(pos)  # 主物品管理界面的点击
            return
    
    def _handle_hover(self, pos):
        if self.current_screen == "main_menu":
            for button in self.buttons:
                button['hover'] = button['rect'].collidepoint(pos)
        
        elif self.current_screen == "item_management":
            if self.selecting_item_for_team:
                # 物品选择界面的悬停
                for button in self.item_selection_buttons:
                    button['hover'] = button['rect'].collidepoint(pos)
            else:
                # 主物品管理界面的悬停
                for button in self.item_management_buttons:
                    button['hover'] = button['rect'].collidepoint(pos)
        
        else:
            # 清除所有悬停状态
            for button in self.buttons:
                button['hover'] = False
            if hasattr(self, 'item_management_buttons'):
                for button in self.item_management_buttons:
                    button['hover'] = False
            if hasattr(self, 'item_selection_buttons'):
                for button in self.item_selection_buttons:
                    button['hover'] = False
        
    def _handle_keypress(self, key):
        if key == pygame.K_ESCAPE:
            if self.current_screen == "champion_selection":
                self.current_screen = "main_menu"
            elif self.current_screen == "battle":
                self.current_screen = "main_menu"
        if key == pygame.K_LEFTBRACKET:
            self.turn_interval_ms = min(5000, self.turn_interval_ms + 250)
        if key == pygame.K_RIGHTBRACKET:
            self.turn_interval_ms = max(250, self.turn_interval_ms - 250)
    
    def _execute_action(self, action):
        print(f"DEBUG: Executing action: {action}") 
        if action == "champion_selection":
            self.current_screen = "champion_selection"
            self._load_available_champions()
        elif action == "item_management":
            self.current_screen = "item_management"
            self._load_item_management_data()
        elif action == "save_game":
            self._save_game()
        elif action == "start_battle":
            if self.current_team1 and self.current_team2:
                self._start_battle()
            else:
                self._show_message("Please select champions for both teams first!")
        elif action == "load_game":
            self._load_game()
        elif action == "game_info":
            self._show_game_info()
        elif action == "exit_game":
            pygame.quit()
            sys.exit()
    
    def _load_item_management_data(self):
        self.available_items = self.game_manager.get_available_items()
        self.item_management_buttons = []
        self._create_item_management_buttons()
    
    def _create_item_management_buttons(self):
        self.item_management_buttons = []
        button_width = 250
        button_height = 50
        start_x = self.screen_width // 2 - button_width // 2
        start_y = 200
        
        buttons = [
            ("View All Items", start_x, start_y, button_width, button_height, "view_items"),
            ("Equip Item to Team 1", start_x, start_y + 70, button_width, button_height, "equip_team1"),
            ("Equip Item to Team 2", start_x, start_y + 140, button_width, button_height, "equip_team2"),
            ("View Team 1 Equipment", start_x, start_y + 210, button_width, button_height, "view_team1_eq"),
            ("View Team 2 Equipment", start_x, start_y + 280, button_width, button_height, "view_team2_eq"),
            ("Back to Main Menu", start_x, start_y + 350, button_width, button_height, "back_to_menu")
        ]
        for text, x, y, w, h, action in buttons:
            self.item_management_buttons.append({
                'text': text,
                'rect': pygame.Rect(x, y, w, h),
                'action': action,
                'hover': False
            })
    
    def _draw_item_management(self):
        title_text = self.fonts['large'].render("Item Management", True, self.colors['accent'])
        self.screen.blit(title_text, (50, 50))

        team1_text = self.fonts['medium'].render(f"Team 1: {len(self.current_team1)} champions", True, self.colors['text'])
        team2_text = self.fonts['medium'].render(f"Team 2: {len(self.current_team2)} champions", True, self.colors['text'])
        self.screen.blit(team1_text, (50, 100))
        self.screen.blit(team2_text, (300, 100))
        for button in self.item_management_buttons:
            color = self.colors['button_hover'] if button['hover'] else self.colors['button']
            pygame.draw.rect(self.screen, color, button['rect'])
            pygame.draw.rect(self.screen, self.colors['border'], button['rect'], 2)
            
            text = self.fonts['small'].render(button['text'], True, self.colors['text'])
            text_rect = text.get_rect(center=button['rect'].center)
            self.screen.blit(text, text_rect)
    
        hint_text = self.fonts['tiny'].render("Note: Full item management available in console version", True, self.colors['warning'])
        self.screen.blit(hint_text, (50, self.screen_height - 50))

    def _handle_item_management_click(self, pos):
        for button in self.item_management_buttons:
            if button['rect'].collidepoint(pos):
                if button['action'] == "view_items":
                    self._show_simple_items_list()
                elif button['action'] == "equip_team1":
                    self._equip_to_team(1)
                elif button['action'] == "equip_team2":
                    self._equip_to_team(2)
                elif button['action'] == "view_team1_eq":
                    self._view_team_equipment(1)
                elif button['action'] == "view_team2_eq":
                    self._view_team_equipment(2)
                elif button['action'] == "back_to_menu":
                    self.current_screen = "main_menu"
                break
    def _show_simple_items_list(self):
        """显示简单的物品列表"""
        message = f"Available Items: {len(self.available_items)} items total\n"
        if self.available_items:
            # 显示前几个物品作为示例
            sample_items = ", ".join(self.available_items[:5])
            message += f"Items include: {sample_items}"
            if len(self.available_items) > 5:
                message += f", and {len(self.available_items) - 5} more..."
        message += "\nUse console version for detailed item management."
        
        self._show_message(message)

    def _show_item_selection_interface(self):
        """显示物品选择界面"""
        if not self.available_items:
            self._show_message("No items available!")
            self.selecting_item_for_team = None
            return
        
        # 创建物品选择按钮
        self.item_selection_buttons = []
        button_width = 300
        button_height = 50
        start_x = self.screen_width // 2 - button_width // 2
        start_y = 150
        
        # 显示可用物品
        for i, item_name in enumerate(self.available_items):
            item = self.game_manager.create_item(item_name)
            if item:
                y_pos = start_y + i * 60
                button_rect = pygame.Rect(start_x, y_pos, button_width, button_height)
                self.item_selection_buttons.append({
                    'rect': button_rect,
                    'item_name': item_name,
                    'item': item,
                    'hover': False
                })
        
        # 添加返回按钮
        back_button_rect = pygame.Rect(start_x, start_y + len(self.available_items) * 60 + 20, 
                                    button_width, button_height)
        self.item_selection_buttons.append({
            'rect': back_button_rect,
            'item_name': "BACK",
            'item': None,
            'hover': False
        })

    def _show_items_list(self):
        items_per_page = 8
        current_page = 0
        item_panel = pygame.Rect(100, 150, 1000, 500)
        pygame.draw.rect(self.screen, self.colors['panel'], item_panel)
        pygame.draw.rect(self.screen, self.colors['border'], item_panel, 2)
        title_text = self.fonts['medium'].render("Available Items", True, self.colors['accent'])
        self.screen.blit(title_text, (item_panel.x + 10, item_panel.y + 10))
        for i, item_name in enumerate(self.available_items[:items_per_page]):
            item = self.game_manager.create_item(item_name)
            if item:
                y_pos = item_panel.y + 50 + i * 50
                item_text = self.fonts['small'].render(f"{item.name} [{item.rarity}]", True, self.colors['text'])
                self.screen.blit(item_text, (item_panel.x + 20, y_pos))
        back_rect = pygame.Rect(item_panel.x + 400, item_panel.y + 450, 200, 40)
        pygame.draw.rect(self.screen, self.colors['button'], back_rect)
        pygame.draw.rect(self.screen, self.colors['border'], back_rect, 2)
        back_text = self.fonts['small'].render("Back", True, self.colors['text'])
        back_text_rect = back_text.get_rect(center=back_rect.center)
        self.screen.blit(back_text, back_text_rect)
        pygame.display.flip()
        waiting = True
        while waiting:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if back_rect.collidepoint(event.pos):
                        waiting = False 

    def _show_equip_interface(self):
        if not self.current_team1 and not self.current_team2:
            self._show_message("No champions available for equipping!")
            return
        self._show_message("Equip feature - Please use console version for full functionality")

    def _show_equipment_view(self):
        if not self.current_team1 and not self.current_team2:
            self._show_message("No champions to view equipment!")
            return
        self._show_message("Equipment view - Please use console version for full functionality")    

    def _show_simple_items_list(self):
        """显示简单的物品列表"""
        message = f"Available Items: {len(self.available_items)} items total\n"
        if self.available_items:
            # 显示前几个物品作为示例
            sample_items = ", ".join(self.available_items[:5])
            message += f"Items include: {sample_items}"
            if len(self.available_items) > 5:
                message += f", and {len(self.available_items) - 5} more..."
        message += "\nUse console version for detailed item management."
        
        self._show_message(message)

    def _handle_champion_click(self, pos):
        available_panel = next((p for p in self.panels if p['name'] == 'available_panel'), None)
        if available_panel:
            for i, champion in enumerate(available_panel['champions']):
                champion_rect = pygame.Rect(
                    available_panel['rect'].x + 20 + (i % 4) * 120,
                    available_panel['rect'].y + 50 + (i // 4) * 80,
                    100, 60
                )
                if champion_rect.collidepoint(pos):
                    self._add_champion_to_team(champion)
                    break
        
        for team_num in [1, 2]:
            team_panel = next((p for p in self.panels if p['name'] == f'team{team_num}_panel'), None)
            if team_panel:
                for i, champion in enumerate(team_panel['champions']):
                    champion_rect = pygame.Rect(
                        team_panel['rect'].x + 20 + (i % 3) * 150,
                        team_panel['rect'].y + 50 + (i // 3) * 80,
                        130, 60
                    )
                    if champion_rect.collidepoint(pos):
                        self._remove_champion_from_team(team_num, i)
                        break

    def _handle_item_selection_click(self, pos):
        """处理物品选择界面的点击"""
        for button in self.item_selection_buttons:
            if button['rect'].collidepoint(pos):
                if button['item_name'] == "BACK":
                    # 返回物品管理界面
                    self.selecting_item_for_team = None
                    self.item_selection_buttons = []
                else:
                    # 选择物品并装备
                    self._equip_selected_item(button['item'])
                break

    def _add_champion_to_team(self, champion_name):
        champion = self.game_manager.create_champion(champion_name)
        if champion:
            if self.selected_team == 1:
                if len(self.current_team1) < 5:
                    self.current_team1.append(champion)
                    self._update_team_panel(1)
            else:
                if len(self.current_team2) < 5:
                    self.current_team2.append(champion)
                    self._update_team_panel(2)
    
    def _remove_champion_from_team(self, team_num, champion_index):
        if team_num == 1 and champion_index < len(self.current_team1):
            self.current_team1.pop(champion_index)
            self._update_team_panel(1)
        elif team_num == 2 and champion_index < len(self.current_team2):
            self.current_team2.pop(champion_index)
            self._update_team_panel(2)
    
    def _update_team_panel(self, team_num):
        team_panel = next((p for p in self.panels if p['name'] == f'team{team_num}_panel'), None)
        if team_panel:
            team_panel['champions'] = self.current_team1 if team_num == 1 else self.current_team2
    
    def _load_available_champions(self):
        available_panel = next((p for p in self.panels if p['name'] == 'available_panel'), None)
        if available_panel:
            available_panel['champions'] = self.game_manager.get_available_champions()
    
    def _start_battle(self):
        result = self.game_manager.start_battle(self.current_team1, self.current_team2)
        if result["success"]:
            self.current_screen = "battle"
            self.battle_active = True
            self.battle_turn = 0
            self._show_message("The battle begins!")
        else:
            self._show_message(f"The battle started with a failure: {result['message']}")
    
    def _save_game(self):
        save_name = f"save_{len(self.game_manager.get_save_files()) + 1}"
        if self.game_manager.save_game(self.current_team1, self.current_team2, save_name):
            self._show_message(f"The game has been saved: {save_name}")
        else:
            self._show_message("Save failed!")
    
    def _load_game(self):
        save_files = self.game_manager.get_save_files()
        if save_files:
            game_data = self.game_manager.load_game(save_files[0])
            if game_data:
                self.current_team1 = game_data["team1"]
                self.current_team2 = game_data["team2"]
                self._update_team_panel(1)
                self._update_team_panel(2)
                self._show_message(f"The game has loaded: {save_files[0]}")
            else:
                self._show_message("Load failed!")
        else:
            self._show_message("No saved file found!")
    
    def _show_game_info(self):
        self._show_message("League of Chang'An - A turn-based combat game based on object-oriented programming")
    
    def _show_message(self, message):
        print(f"Message: {message}")
    
    def _update(self):
        if self.battle_active and self.current_screen == "battle":
            now = pygame.time.get_ticks()
            if now - self._last_turn_ms < self.turn_interval_ms:
                return
            self._last_turn_ms = now
            result = self.game_manager.execute_battle_turn(self.current_team1, self.current_team2)
            if result.get("battle_ended"):
                self.battle_active = False
                self.current_screen = "main_menu"
                self._show_message(f"The battle is over! The winner is: {result['winner']}")
            else:
                self.battle_turn += 1
    
    def _draw(self):
        self.screen.fill(self.colors['background'])
        
        self._draw_background()
        
        if self.current_screen == "main_menu":
            self._draw_main_menu()
        elif self.current_screen == "champion_selection":
            self._draw_champion_selection()
        elif self.current_screen == "battle":
            self._draw_battle()
        elif self.current_screen == "item_management":  
            if self.selecting_item_for_team:
                self._draw_item_selection()  # 物品选择界面
            else:
                self._draw_item_management() 
    def _draw_background(self):
        for x in range(0, self.screen_width, 100):
            for y in range(0, self.screen_height, 100):
                pygame.draw.rect(self.screen, (30, 35, 50), (x, y, 100, 100), 1)
        
        self._draw_decorative_elements()
    
    def _draw_decorative_elements(self):
        points = []
        for x in range(0, self.screen_width, 50):
            y = 50 + 30 * math.sin(x * 0.01)
            points.append((x, y))
        
        if len(points) > 1:
            pygame.draw.lines(self.screen, self.colors['accent'], False, points, 2)
    
    def _draw_main_menu(self):
        title_text = self.fonts['title'].render("League of Chang'An", True, self.colors['accent'])
        title_rect = title_text.get_rect(center=(self.screen_width // 2, 150))
        self.screen.blit(title_text, title_rect)
        
        subtitle_text = self.fonts['large'].render("league of chang'an", True, self.colors['text'])
        subtitle_rect = subtitle_text.get_rect(center=(self.screen_width // 2, 200))
        self.screen.blit(subtitle_text, subtitle_rect)
        
        for button in self.buttons:
            color = self.colors['button_hover'] if button['hover'] else self.colors['button']
            pygame.draw.rect(self.screen, color, button['rect'])
            pygame.draw.rect(self.screen, self.colors['border'], button['rect'], 2)
            
            text = self.fonts['medium'].render(button['text'], True, self.colors['text'])
            text_rect = text.get_rect(center=button['rect'].center)
            self.screen.blit(text, text_rect)
    
    def _draw_champion_selection(self):
        title_text = self.fonts['large'].render("Champion Selection", True, self.colors['accent'])
        self.screen.blit(title_text, (50, 50))
        
        for panel in self.panels:
            self._draw_panel(panel)
        
        self._draw_team_selection_buttons()
    
    def _draw_panel(self, panel):
        pygame.draw.rect(self.screen, self.colors['panel'], panel['rect'])
        pygame.draw.rect(self.screen, self.colors['border'], panel['rect'], 2)
        
        title_text = self.fonts['medium'].render(panel['title'], True, self.colors['text'])
        self.screen.blit(title_text, (panel['rect'].x + 10, panel['rect'].y + 10))
        
        if 'champions' in panel:
            for i, champion in enumerate(panel['champions']):
                if isinstance(champion, str): 
                    self._draw_available_champion(panel, i, champion)
                else:  
                    self._draw_team_champion(panel, i, champion)
    
    def _draw_available_champion(self, panel, index, champion_name):
        x = panel['rect'].x + 20 + (index % 4) * 120
        y = panel['rect'].y + 50 + (index // 4) * 80
        
        champion_rect = pygame.Rect(x, y, 100, 60)
        pygame.draw.rect(self.screen, self.colors['button'], champion_rect)
        pygame.draw.rect(self.screen, self.colors['border'], champion_rect, 1)
        
        name_text = self.fonts['small'].render(champion_name, True, self.colors['text'])
        name_rect = name_text.get_rect(center=champion_rect.center)
        self.screen.blit(name_text, name_rect)
    
    def _draw_team_champion(self, panel, index, champion):
        x = panel['rect'].x + 20 + (index % 3) * 150
        y = panel['rect'].y + 50 + (index // 3) * 80
        
        champion_rect = pygame.Rect(x, y, 130, 60)
        pygame.draw.rect(self.screen, self.colors['secondary'], champion_rect)
        pygame.draw.rect(self.screen, self.colors['border'], champion_rect, 1)
        
        name_text = self.fonts['small'].render(champion.name, True, self.colors['text'])
        self.screen.blit(name_text, (x + 5, y + 5))
        
        level_text = self.fonts['tiny'].render(f"Lv.{champion.level}", True, self.colors['text'])
        self.screen.blit(level_text, (x + 5, y + 25))
        
        hp_text = self.fonts['tiny'].render(f"HP: {champion.health}/{champion.max_health}", True, self.colors['text'])
        self.screen.blit(hp_text, (x + 5, y + 40))
    
    def _draw_team_selection_buttons(self):
        team1_rect = self.team_button_rects['team1']
        color1 = self.colors['accent'] if self.selected_team == 1 else self.colors['button']
        pygame.draw.rect(self.screen, color1, team1_rect)
        pygame.draw.rect(self.screen, self.colors['border'], team1_rect, 1)
        
        team1_text = self.fonts['small'].render("Choose team1", True, self.colors['text'])
        team1_text_rect = team1_text.get_rect(center=team1_rect.center)
        self.screen.blit(team1_text, team1_text_rect)
        
        team2_rect = self.team_button_rects['team2']
        color2 = self.colors['accent'] if self.selected_team == 2 else self.colors['button']
        pygame.draw.rect(self.screen, color2, team2_rect)
        pygame.draw.rect(self.screen, self.colors['border'], team2_rect, 1)
        
        team2_text = self.fonts['small'].render("Choose team2", True, self.colors['text'])
        team2_text_rect = team2_text.get_rect(center=team2_rect.center)
        self.screen.blit(team2_text, team2_text_rect)
    
    def _draw_battle(self):
        title_text = self.fonts['large'].render("The battle is in progress", True, self.colors['accent'])
        self.screen.blit(title_text, (50, 50))
        
        turn_text = self.fonts['medium'].render(f"turn: {self.battle_turn}", True, self.colors['text'])
        self.screen.blit(turn_text, (50, 100))
        speed_text = self.fonts['tiny'].render(f"Speed: Per turn {self.turn_interval_ms}ms  (press [ Speed up)", True, self.colors['text'])
        self.screen.blit(speed_text, (50, 120))
        
        self._draw_battle_teams()
    
    def _draw_battle_teams(self):
        team1_text = self.fonts['medium'].render("team1", True, self.colors['text'])
        self.screen.blit(team1_text, (50, 150))
        
        for i, champion in enumerate(self.current_team1):
            y = 180 + i * 80
            self._draw_battle_champion(champion, 50, y, 1)
        
        team2_text = self.fonts['medium'].render("team2", True, self.colors['text'])
        self.screen.blit(team2_text, (650, 150))
        
        for i, champion in enumerate(self.current_team2):
            y = 180 + i * 80
            self._draw_battle_champion(champion, 650, y, 2)
    
    def _draw_battle_champion(self, champion, x, y, team):
        champion_rect = pygame.Rect(x, y, 200, 60)
        
        color = self.colors['primary'] if team == 1 else self.colors['secondary']
        pygame.draw.rect(self.screen, color, champion_rect)
        pygame.draw.rect(self.screen, self.colors['border'], champion_rect, 2)
        
        name_text = self.fonts['small'].render(champion.name, True, self.colors['text'])
        self.screen.blit(name_text, (x + 5, y + 5))
        
        health_percent = champion.health / champion.max_health
        health_width = int(190 * health_percent)
        health_rect = pygame.Rect(x + 5, y + 25, health_width, 15)
        health_color = self.colors['success'] if health_percent > 0.5 else self.colors['warning'] if health_percent > 0.25 else self.colors['error']
        pygame.draw.rect(self.screen, health_color, health_rect)
        pygame.draw.rect(self.screen, self.colors['text'], health_rect, 1)
        
        hp_text = self.fonts['tiny'].render(f"{champion.health}/{champion.max_health}", True, self.colors['text'])
        self.screen.blit(hp_text, (x + 5, y + 45))
        
        status = "survive" if champion.is_alive else "die"
        status_color = self.colors['success'] if champion.is_alive else self.colors['error']
        status_text = self.fonts['tiny'].render(status, True, status_color)
        self.screen.blit(status_text, (x + 100, y + 45))

    def _draw_item_management(self):
        self.screen.fill(self.colors['background'])
        title_text = self.fonts['large'].render("Item Management", True, self.colors['accent'])
        title_rect = title_text.get_rect(center=(self.screen_width // 2, 80))
        self.screen.blit(title_text, title_rect)

        team1_status = f"Team 1: {len(self.current_team1)} champions"
        team2_status = f"Team 2: {len(self.current_team2)} champions"
        
        team1_text = self.fonts['medium'].render(team1_status, True, self.colors['text'])
        team2_text = self.fonts['medium'].render(team2_status, True, self.colors['text'])
        
        self.screen.blit(team1_text, (100, 120))
        self.screen.blit(team2_text, (self.screen_width - 300, 120))

        for button in self.item_management_buttons:
            color = self.colors['button_hover'] if button['hover'] else self.colors['button']
            pygame.draw.rect(self.screen, color, button['rect'])
            pygame.draw.rect(self.screen, self.colors['border'], button['rect'], 2)
            
            text = self.fonts['small'].render(button['text'], True, self.colors['text'])
            text_rect = text.get_rect(center=button['rect'].center)
            self.screen.blit(text, text_rect)
        hint_text = self.fonts['tiny'].render("Click buttons to manage items. Full functionality in console version.", 
                                            True, self.colors['info'])
        self.screen.blit(hint_text, (50, self.screen_height - 30))

    def _equip_to_team(self, team_num):
        team = self.current_team1 if team_num == 1 else self.current_team2
        if not team:
            self._show_message(f"Team {team_num} has no champions!")
            return
        self.selecting_item_for_team = team_num
        self._show_item_selection_interface()


    def _equip_selected_item(self, item):
        """装备选中的物品"""
        team = self.current_team1 if self.selecting_item_for_team == 1 else self.current_team2
        
        if not team:
            self._show_message("No champions available!")
            self.selecting_item_for_team = None
            self.item_selection_buttons = []
            return
        
        # 选择英雄（这里简化处理，装备给第一个英雄）
        champion = team[0]
        
        if champion.equip_item(item):
            self._show_message(f"Successfully equipped {item.name} to {champion.name}!")
            
            # 显示装备效果
            stats = item.get_stats()
            effect_message = f"Effects: "
            for stat, value in stats.items():
                if value > 0:
                    effect_message += f"{stat}+{value} "
            effect_message += f"\nSpecial: {item.get_special_ability()}"
            self._show_message(effect_message)
        else:
            self._show_message(f"Failed to equip {item.name} - equipment slots may be full!")
        
        # 返回物品管理界面
        self.selecting_item_for_team = None
        self.item_selection_buttons = []

    def _view_team_equipment(self, team_num):
        team = self.current_team1 if team_num == 1 else self.current_team2
        if not team:
            self._show_message(f"Team {team_num} has no champions!")
            return
        
        equipped_count = 0
        for champion in team:
            equipped_count += len(champion._equipped_items)
        
        self._show_message(f"Team {team_num}: {equipped_count} items equipped across {len(team)} champions")

    def _draw_item_selection(self):
        """绘制物品选择界面"""
        self.screen.fill(self.colors['background'])
        
        # 标题
        title_text = self.fonts['large'].render("Select Item to Equip", True, self.colors['accent'])
        title_rect = title_text.get_rect(center=(self.screen_width // 2, 80))
        self.screen.blit(title_text, title_rect)
        
        # 队伍信息
        team_text = self.fonts['medium'].render(f"For Team {self.selecting_item_for_team}", True, self.colors['text'])
        team_rect = team_text.get_rect(center=(self.screen_width // 2, 120))
        self.screen.blit(team_text, team_rect)
        
        # 绘制物品按钮
        for button in self.item_selection_buttons:
            color = self.colors['button_hover'] if button['hover'] else self.colors['button']
            pygame.draw.rect(self.screen, color, button['rect'])
            pygame.draw.rect(self.screen, self.colors['border'], button['rect'], 2)
            
            if button['item_name'] == "BACK":
                text = self.fonts['small'].render("← Back to Item Management", True, self.colors['text'])
            else:
                item = button['item']
                # 显示物品名称和稀有度
                text = self.fonts['small'].render(f"{item.name} [{item.rarity}]", True, self.colors['text'])
                
                # 在按钮下方显示物品属性
                stats = item.get_stats()
                stat_text = ""
                for stat, value in stats.items():
                    if value > 0:
                        stat_text += f"{stat}+{value} "
                
                stat_surface = self.fonts['tiny'].render(stat_text, True, self.colors['info'])
                self.screen.blit(stat_surface, (button['rect'].x + 10, button['rect'].y + 30))
            
            text_rect = text.get_rect(center=button['rect'].center)
            self.screen.blit(text, text_rect)


def main():
        try:
            ui = GraphicsUI()
            ui.run()
        except Exception as e:
            print(f"Error running graphics UI: {e}")
        import traceback
        traceback.print_exc()
if __name__ == "__main__":
    main()